package com.collect.cameroon.zhiScene.zhiPublic;

import androidx.annotation.NonNull;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.collect.cameroon.R;
import com.collect.cameroon.zhiBase.BaseActivity;
import com.collect.cameroon.zhiGlobal.zhiAppSettings.ZHIProjectConfigs;
import com.collect.cameroon.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.cameroon.zhiUtils.zhiVersion.ZHIVersionClient;
import com.collect.cameroon.zhiUtils.zhiVersion.ZHIVersionIMPL;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

@SuppressLint("NonConstantResourceId")
@Route(path = ZHIProjectRouter.ZHI_APP_UPDATE)
public class NEXTVersionUpdateActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {

    @BindView(R.id.iv_product_logo)
    ImageView iv_product_logo;
    @BindView(R.id.tv_product_name)
    TextView tv_product_name;
    @BindView(R.id.tv_progress)
    TextView tv_progress;
    @BindView(R.id.pb_progress)
    ProgressBar pb_progress;
    @BindView(R.id.btn_install)
    TextView btn_install;
    @BindView(R.id.btn_cancel)
    TextView btn_cancel;

    private static final int RC_CAMERA_AND_STORAGE = 112;
    private static final int RC_INSTALL_PCK = 10086;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_version_update;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initView() {
        getNeedPermissions();
    }

    @OnClick({R.id.btn_cancel, R.id.btn_install})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel: {
                finish();
                break;
            }
            case R.id.btn_install: {
                getNeedPermissions();
                break;
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onRationaleAccepted(int requestCode) {

    }

    @Override
    public void onRationaleDenied(int requestCode) {

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @SuppressLint("SetTextI18n")
    @AfterPermissionGranted(RC_CAMERA_AND_STORAGE)
    public void allPass() {
        ZHIVersionClient.startDownload(ZHIVersionIMPL.productLink, (currentBytes, contentLength, done) -> {
            int progress = (int) (currentBytes * 100 / contentLength);
            pb_progress.setProgress(progress);
            tv_progress.setText(progress + "%");

            tv_progress.setVisibility(View.VISIBLE);
            btn_install.setVisibility(View.GONE);
            btn_cancel.setVisibility(View.GONE);

//            pb_progress.setVisibility(done ? View.GONE : View.VISIBLE);
//            tv_progress.setVisibility(done ? View.GONE : View.VISIBLE);
//            btn_install.setVisibility(done ? View.VISIBLE : View.GONE);
//            btn_cancel.setVisibility(done ? View.VISIBLE : View.GONE);

            if (done) {
                //安装文件
                ZHIVersionIMPL.startInstallApk(ZHIVersionIMPL.productApkLocalPath);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            //当从软件设置界面，返回当前程序时候
            if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
                getNeedPermissions();
            } else if (requestCode == RC_INSTALL_PCK) {
                getNeedPermissions();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void getNeedPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (getPackageManager().canRequestPackageInstalls()) {
                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions), RC_CAMERA_AND_STORAGE, reqPerms);
            } else {
                getUnknowAppPage();
            }
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions), RC_CAMERA_AND_STORAGE, reqPerms);
        }
    }

    public void getUnknowAppPage() {
        try {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                intent.setData(Uri.parse("package:" + ZHIProjectConfigs.PACKAGE_NAME));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivityForResult(intent, RC_INSTALL_PCK);
            } else {
                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions), RC_CAMERA_AND_STORAGE, reqPerms);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    String[] reqPerms = {
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
            android.Manifest.permission.READ_EXTERNAL_STORAGE
    };
}